<?php namespace App\Http\Controllers\Api;

use App\Goods;
use App\GoodsSpu;
use App\GoodsStockSyncLog;
use App\Http\Controllers\Controller;
use App\Http\Services\SyncData;
use App\OrderAddress;
use App\OrderItem;
use App\Orders;
use App\UserInfo;

class SyncController extends Controller
{
    public static function syncOrderDetail(){
        $nowTime = time();
        $orders = Orders::whereBetween("sync_time",[$nowTime-3600,$nowTime])->whereNotNull("order_sn")->whereNotIn("status",[5,8])->get();
        if(count($orders) > 0){
            foreach ($orders as $order){
                /** @var Orders $order */
                $theSyncData = SyncData::getOrdersDetail($order->order_sn);
                if($theSyncData->status == 1){
                    if($theSyncData->data->page->totalResult > 0){
                        $orderGets = $theSyncData->data->orderListGets;
                        if(count($orderGets) > 0){
                            foreach ($orderGets as $orderGet){
                                if($orderGet->order_status == 1){
                                    if($orderGet->shipping_status == 6){
                                        $order->status = 3;
                                    }else{
                                        $order->status = 2;
                                    }
                                }elseif($orderGet->order_status == 5){
                                    $order->status = 5;
                                }elseif($orderGet->order_status == 3){
                                    $order->status = 6;
                                }

                                $order->mc_order_status = $orderGet->order_status;
                                if(is_null($order->express_num))$order->express_num = $orderGet->shipping_sn;
                                if(is_null($order->express_time))$order->express_time = $orderGet->shipping_time_fh;
                                $order->sync_time = time();
                                $order->save();
                            }
                        }
                    }
                }
            }
        }

        return true;
    }

    public static function syncAddOrder($orderId){
        $thatOrder = Orders::whereId($orderId)->first();
        if(!$thatOrder)
            return false;

        $thisUser=UserInfo::whereUserId($thatOrder->user_id)->first();
        $userName = $thisUser ? $thisUser->nickname : "-";

        /** @var OrderAddress $address */
        $address=OrderAddress::whereId($thatOrder->address_id)->first();
        $receive_name = $address ? $address->consignee : "";
        $receive_province = $address ? $address->province : "";
        $receive_city = $address ? $address->city : "";
        $receive_district = $address ? $address->area : "";
        $receive_address = $address ? $address->address : "-";
        $receive_mobile = $address ? $address->phone : "";

        $thatSyncData = new SyncData();
        $thatSyncData->setDealCode($thatOrder->order_num);
        $thatSyncData->setLylx(0);
        $thatSyncData->setSdCode("ht004");
//        $thatSyncData->setSdCode("12332112");
        $thatSyncData->setUserName($userName);
        $thatSyncData->setPayCode("xsptzf");
        $thatSyncData->setShippingCode("ZTO");
        $thatSyncData->setReceiverName($receive_name);
        $thatSyncData->setReceiverCountry("中国");
        $thatSyncData->setReceiverProvince($receive_province);
        $thatSyncData->setReceiverCity($receive_city);
        $thatSyncData->setReceiverDistrict($receive_district);
        $thatSyncData->setReceiverAddress($receive_address);
        $thatSyncData->setReceiverAddr($receive_address);
        $thatSyncData->setReceiverMobile($receive_mobile);
        $thatSyncData->setAddTime($thatOrder->created_at);
        $thatSyncData->setPayTime($thatOrder->pay_time);
        $thatSyncData->setPayStatus($thatOrder->is_pay);
        $thatSyncData->setShippingFee($thatOrder->express_fee);
        $thatSyncData->setOrderAmount($thatOrder->s_amount);
        $thatSyncData->setPayment($thatOrder->s_amount);
        $thatSyncData->setIsCod(0);

        $items =[];
        $thatOrderItems = OrderItem::whereOrderId($orderId)->get();
        if(count($thatOrderItems) > 0){
            foreach ($thatOrderItems as $thatOrderItem){
                $spu   = GoodsSpu::whereId($thatOrderItem->goods_spu_id)->first();
                $goods = Goods::whereId($thatOrderItem->goods_id)->first();
                $theItem = [
                    "deal_code"   => $thatOrderItem->item_num,
                    "sku"         => $spu ? $spu->specification_code : '',
                    "goods_sn"    => $goods ? $goods->ssn : "",
                    "goods_name"  => $goods ? $goods->name : "-",
                    "shop_price"  => $thatOrderItem->s_price,
                    "goods_price" => $thatOrderItem->s_price,
                    "goods_number"=> $thatOrderItem->num,
                    "is_gift"     => $thatOrderItem->s_price==0 ? 1 : 0
                ];

                array_push($items,$theItem);
            }
        }
        $thatSyncData->setItems($items);

        $result = SyncData::addOrders($thatSyncData);

        if($result && isset($result->status) && $result->status == 1){
            if(isset($result->data->order_sn)){
                $thatOrder->order_sn = $result->data->order_sn;
            }
            $thatOrder->sync_time = time();
            $thatOrder->save();
        }

        return $result;
    }

//    public static function syncUpdateOrder($orderId){
//        $thatOrder = Orders::whereId($orderId)->first();
//        if(!$thatOrder)
//            return false;
//
//        /** @var OrderAddress $address */
//        $address=OrderAddress::whereId($thatOrder->address_id)->first();
//        $receive_name = $address ? $address->consignee : "";
//        $receive_province = $address ? $address->province : "";
//        $receive_city = $address ? $address->city : "";
//        $receive_district = $address ? $address->area : "";
//        $receive_address = $address ? $address->address : "-";
//        $receive_mobile = $address ? $address->phone : "";
//
//
//    }

    public function syncStock(){
        $nowTime = time();
        $allGoods = Goods::whereBetween("sync_time",[$nowTime-3600,$nowTime])->orWhere("sync_time","=",0)->limit(10)->get();
        $i=0;
        if(count($allGoods) > 0){
            foreach ($allGoods as $good){
                $i++;
                self::syncStockByGoodsDetail($good->id);
            }
        }

        self::syncOrderDetail();

        return "success【".$i."】";
    }

    public static function syncStockByGoodsDetail($goodsId=0){
        $thatGoods = Goods::whereId($goodsId)->first();
        if(!$thatGoods || ($thatGoods && is_null($thatGoods->ssn))){
            return false;
        }

        $thatBarCode = $thatGoods->ssn;

        $page = 1;
        $theSyncData = SyncData::getGoodsStock($thatBarCode,$page);
        if($theSyncData->status == 1){
            if($theSyncData->data->filter->record_count > 0){
                $stockDatas = $theSyncData->data->data;
                self::setSyncData($stockDatas);
            }

            $pageCount = $theSyncData->data->filter->page_count;
            while ($pageCount > $page){
                $page++;
                $thatSyncData = SyncData::getGoodsStock($thatBarCode,$page);

                if($thatSyncData->status == 1) {
                    if ($thatSyncData->data->filter->record_count > 0) {
                        $theStockDatas = $thatSyncData->data->data;
                        self::setSyncData($theStockDatas);
                    }
                }
            }
        }

        return true;
    }

    public static function setSyncData($datas){
        if(count($datas) > 0){
            foreach ($datas as $data){
                $thatGoodsSpu = GoodsSpu::whereSpecificationCode($data->sku)->first();
                if($thatGoodsSpu){
                    $thatGoods = Goods::whereId($thatGoodsSpu->goods_id)->first();
                    if($thatGoods){
                        $thatGoods->sync_time = time();
                        $thatGoods->save();
                    }

                    $lastStock = $thatGoodsSpu->stock;

                    $thatGoodsSpu->stock = $data->num;
                    $thatGoodsSpu->sync_time = time();
                    $thatGoodsSpu->save();

                    //记录日志
                    $thatNewLog = new GoodsStockSyncLog();
                    $thatNewLog->goods_id = $thatGoodsSpu->goods_id;
                    $thatNewLog->goods_code = $data->goods_code;
                    $thatNewLog->goods_spu_id = $thatGoodsSpu->id;
                    $thatNewLog->sku_code     = $data->sku;
                    $thatNewLog->color_code = $data->color_code;
                    $thatNewLog->color_name = $data->color_name;
                    $thatNewLog->size_code = $data->size_code;
                    $thatNewLog->size_name = $data->size_name;
                    $thatNewLog->num = $data->num;
                    $thatNewLog->lock_num = $data->lock_num;
                    $thatNewLog->road_num = $data->road_num;
                    $thatNewLog->ck_name = $data->ck_name;
                    $thatNewLog->ck_dm = $data->ck_dm;
                    $thatNewLog->kw_name = $data->kw_name;
                    $thatNewLog->last_num = $lastStock;
                    $thatNewLog->remark = "sync_success";
                    $thatNewLog->save();
                }
            }
        }

        return true;
    }
}